<template>
  <div v-loading="dataListLoading" class="page-container-padding">
    <div style="margin-bottom: 10px">
      <el-select
        v-model="curVariety"
        filterable
        size="mini"
        style="width: 140px"
        @change="handleVarietyChange"
      >
        <el-option
          v-for="(item, index) in varietyList"
          :key="index"
          :value="item.variety_en"
          :label="item.variety_name + item.variety_en"
        ></el-option>
      </el-select>
      <el-select
        v-model="isShowOwn"
        size="mini"
        style="width: 120px; margin-left: 6px"
        @change="handleVarietyChange"
      >
        <el-option :value="true" label="我的数据图表"></el-option>
        <el-option :value="false" label="全部数据图表"></el-option>
      </el-select>
      <span style="margin-left: 6px">
        <el-input
          v-model="keyword"
          clearable
          style="width: 220px"
          placeholder="输入关键字查询图形或数据表"
          size="mini"
          @change="handleVarietyChange"
        ></el-input>
      </span>
      <el-button
        style="margin: 0 6px"
        type="primary"
        size="mini"
        @click="handleVarietyChange"
      >
        查询
      </el-button>
    </div>
    <div v-show="curVariety" class="folders">
      <div v-for="group in folderList" :key="group.id" class="folder-box">
        <vab-icon
          class="folder-icon"
          :icon="
            group.id === folderOpenId
              ? ['fas', 'folder-open']
              : ['fas', 'folder']
          "
        ></vab-icon>
        <span class="folder-name" @click="toShowGroupContents(group)">
          {{ group.name }}
        </span>
      </div>
      <div class="folder-box" @click="toCreateNewGroup">
        <vab-icon :icon="['fas', 'user-cog']"></vab-icon>
        <span class="folder-name">配置</span>
      </div>
      <div>
        <el-checkbox v-model="useNewColors">使用新配色方案</el-checkbox>
      </div>
    </div>
    <el-tabs v-model="curTabName" type="border-card" @tab-click="tabClickEvent">
      <el-tab-pane name="chartList" :label="chartListLable">
        <div v-if="chartList.length < 1">
          <el-empty description="查询结果没有数据图形"></el-empty>
        </div>
        <div v-else>
          <el-table border stripe :data="chartList">
            <el-table-column label="图ID" width="100px">
              <template slot-scope="scope">
                <span>{{ (scope.row.id + '').padStart(3, '0') }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="chart_type_zh"
              label="类型"
              width="120px"
            ></el-table-column>
            <el-table-column
              prop="name"
              label="标题"
              min-width="320px"
            ></el-table-column>
            <el-table-column
              prop="startdate"
              label="开始日期"
              width="100px"
            ></el-table-column>
            <el-table-column label="查看图形" width="100px" align="center">
              <template slot-scope="scope">
                <span
                  style="color: #0077cc; cursor: pointer"
                  @click="toShowChartPopup(scope.$index)"
                >
                  <vab-icon :icon="['fas', 'chart-pie']"></vab-icon>
                </span>
              </template>
            </el-table-column>
            <el-table-column label="修改配置" width="100px" align="center">
              <template slot-scope="scope">
                <span
                  style="color: #0077cc; cursor: pointer"
                  @click="optionMyChart(scope.$index)"
                >
                  <vab-icon :icon="['fas', 'tools']"></vab-icon>
                </span>
              </template>
            </el-table-column>
            <el-table-column label="归档" width="120px" align="center">
              <template slot-scope="scope">
                <div class="table-select">
                  <el-select
                    v-model="scope.row.group_id"
                    size="mini"
                    @change="(v) => chartGroupChanged(v, scope.row, scope.$index)"
                  >
                    <el-option
                      v-for="g in folderList"
                      :key="g.id"
                      :value="g.id"
                      :label="g.name"
                    ></el-option>
                  </el-select>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="sorted"
              label="序号"
              width="100px"
              align="center"
            ></el-table-column>
            <el-table-column label="删除" width="100px" align="center">
              <template slot-scope="scope">
                <span
                  style="color: #ff5500; cursor: pointer"
                  @click="delMyChart(scope.$index)"
                >
                  <vab-icon :icon="['fas', 'trash-alt']"></vab-icon>
                </span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
      <el-tab-pane name="chart" :label="chartTabLabel">
        <div v-if="chartList.length < 1">
          <el-empty description="查询结果没有图形"></el-empty>
        </div>
        <div v-else style="display: flex; flex-flow: wrap">
          <div v-for="(item, index) in chartList" :key="index">
            <div class="chart-card">
              <span class="action-btns">
                <el-button
                  circle
                  icon="el-icon-delete"
                  type="danger"
                  @click="delMyChart(index)"
                ></el-button>
                <el-button
                  circle
                  icon="el-icon-s-operation"
                  type="primary"
                  @click="optionMyChart(index)"
                ></el-button>
                <el-button
                  circle
                  icon="el-icon-document-copy"
                  type="success"
                  size="mini"
                  @click="toCopyChart(index)"
                ></el-button>
              </span>
              <div
                :id="'chartDiv' + item.id"
                style="height: 300px; width: 500px; position: relative"
              >
                <vab-chart
                  autoresize
                  theme="vab-echarts-theme"
                  :option="item.option"
                ></vab-chart>
                <div
                  v-show="item.showWatermark"
                  style="font-size: 20px; color: rgba(0, 0, 0, 0.2)"
                >
                  <div style="position: absolute; top: 96px; left: 80px">
                    {{ item.watermark }}
                  </div>
                  <div style="position: absolute; top: 180px; right: 80px">
                    {{ item.watermark }}
                  </div>
                </div>
              </div>
              <span class="chart-info">
                <span>{{ item.sorted }}</span>
              </span>
              <!-- 对比解读 -->
              <div v-if="item.link_ratios.length > 0" class="link-ratio-box">
                <div>
                  <span>对比解读：</span>
                  <span class="compared-box">
                    <el-button
                      circle
                      sizie="mini"
                      :type="item.compared === 'day' ? 'primary' : 'infor'"
                      @click="toGetChartCompared(index, 'day')"
                    >
                      日
                    </el-button>
                    <el-button
                      circle
                      sizie="mini"
                      :type="item.compared === 'week' ? 'primary' : 'infor'"
                      @click="toGetChartCompared(index, 'week')"
                    >
                      周
                    </el-button>
                    <el-button
                      circle
                      sizie="mini"
                      :type="item.compared === 'month' ? 'primary' : 'infor'"
                      @click="toGetChartCompared(index, 'month')"
                    >
                      月
                    </el-button>
                    <el-button
                      circle
                      sizie="mini"
                      :type="item.compared === 'quarter' ? 'primary' : 'infor'"
                      @click="toGetChartCompared(index, 'quarter')"
                    >
                      季
                    </el-button>
                    <el-button
                      circle
                      sizie="mini"
                      :type="item.compared === 'annual' ? 'primary' : 'infor'"
                      @click="toGetChartCompared(index, 'annual')"
                    >
                      年
                    </el-button>
                    <span style="margin-left: 8px">
                      <el-checkbox v-model="item.linkage">图形联动</el-checkbox>
                    </span>
                    <span style="margin-left: 8px">
                      <el-checkbox
                        v-model="item.showWatermark"
                        @change="
                          (v) => {
                            toggleWatermark(index, v)
                          }
                        "
                      >
                        水印
                      </el-checkbox>
                    </span>
                  </span>
                </div>
                <div
                  v-if="!item.editCompared"
                  v-loading="item.compareLoading"
                  element-loading-spinner="el-icon-loading"
                  @dblclick="toEditCompareText(item)"
                >
                  <span v-html="item.compareText"></span>
                </div>
                <div v-else>
                  <el-input
                    v-model="item.comparePlainText"
                    type="textarea"
                    @blur="toStoreCompareText(item)"
                  ></el-input>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane name="sheet" :label="sheetTabLabel">
        <div v-if="sheetList.length < 1">
          <el-empty description="查询结果下没有数据表"></el-empty>
        </div>
        <div v-else>
          <el-table border :data="sheetList">
            <el-table-column label="表ID" width="80px">
              <template slot-scope="scope">
                <span>{{ (scope.row.id + '').padStart(3, '0') }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="name"
              label="名称"
              min-width="320px"
            ></el-table-column>
            <el-table-column label="相关图形" align="center" width="100px">
              <template slot-scope="scope">
                <span
                  style="color: #0077cc; cursor: pointer"
                  @click="toShowSheetCharts(scope.$index)"
                >
                  <span style="margin-right: 5px">
                    {{ scope.row.chart_count }}
                  </span>
                  <vab-icon :icon="['fas', 'poll']"></vab-icon>
                </span>
              </template>
            </el-table-column>
            <el-table-column label="查看与导出" align="center" width="100px">
              <template slot-scope="scope">
                <span
                  style="color: #0077cc; cursor: pointer"
                  @click="toShowSheetPopup(scope.$index)"
                >
                  <vab-icon :icon="['fas', 'eye']"></vab-icon>
                </span>
                <span style="width: 10px; display: inline-block"></span>
                <span
                  style="color: #49a246; cursor: pointer"
                  @click="toExportSheetData(scope.$index)"
                >
                  <vab-icon :icon="['fas', 'file-download']"></vab-icon>
                </span>
              </template>
            </el-table-column>
            <el-table-column label="归档" width="120px" align="center">
              <template slot-scope="scope">
                <div class="table-select">
                  <el-select
                    v-model="scope.row.group_id"
                    size="mini"
                    @change="(v) => sheetGroupChanged(v, scope.row, scope.$index)"
                  >
                    <el-option
                      v-for="g in folderList"
                      :key="g.id"
                      :value="g.id"
                      :label="g.name"
                    ></el-option>
                  </el-select>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="sorted"
              label="序号"
              width="100px"
              align="center"
            ></el-table-column>
            <el-table-column label="删除" width="100px" align="center">
              <template slot-scope="scope">
                <span
                  style="color: #ff5500; cursor: pointer"
                  @click="delMySheet(scope.$index)"
                >
                  <vab-icon :icon="['fas', 'trash-alt']"></vab-icon>
                </span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 查看图形的弹窗 -->
    <el-dialog
      v-if="showChartDialog"
      :visible.sync="showChartDialog"
      :title="currentDialogChartName"
      width="550px"
    >
      <div id="dialogChart">
        <vab-chart
          ref="popChart"
          autoresize
          theme="vab-echarts-theme"
          :option="currentDialogChartOption"
        ></vab-chart>
        <div
          v-show="currentDialogChartData.showWatermark"
          style="font-size: 20px; color: rgba(0, 0, 0, 0.2)"
        >
          <div style="position: absolute; top: 96px; left: 80px">
            {{ currentDialogChartWatermark }}
          </div>
          <div style="position: absolute; top: 180px; right: 80px">
            {{ currentDialogChartWatermark }}
          </div>
        </div>
      </div>
      <!-- 对比解读 -->
      <div v-if="currentDialogLinkRatios.length > 0" class="link-ratio-box">
        <div>
          <span>对比解读：</span>
          <el-tooltip
            class="item"
            effect="dark"
            content="点击复制图形"
            placement="top-start"
          >
            <el-button
              circle
              style="transform: scale(0.7); float: right"
              icon="el-icon-document-copy"
              type="success"
              size="mini"
              @click="toCopyPopupChart"
            ></el-button>
          </el-tooltip>
          <span class="compared-box">
            <el-button
              circle
              sizie="mini"
              style="transform: scale(0.7)"
              :type="currentDialogChartData.compared === 'day' ? 'primary' : 'infor'"
              @click="toGetDialogChartCompared('day')"
            >
              日
            </el-button>
            <el-button
              circle
              sizie="mini"
              style="transform: scale(0.7)"
              :type="currentDialogChartData.compared === 'week' ? 'primary' : 'infor'"
              @click="toGetDialogChartCompared('week')"
            >
              周
            </el-button>
            <el-button
              circle
              sizie="mini"
              style="transform: scale(0.7)"
              :type="currentDialogChartData.compared === 'month' ? 'primary' : 'infor'"
              @click="toGetDialogChartCompared('month')"
            >
              月
            </el-button>
            <el-button
              circle
              sizie="mini"
              style="transform: scale(0.7)"
              :type="currentDialogChartData.compared === 'quarter' ? 'primary' : 'infor'"
              @click="toGetDialogChartCompared('quarter')"
            >
              季
            </el-button>
            <el-button
              circle
              sizie="mini"
              style="transform: scale(0.7)"
              :type="currentDialogChartData.compared === 'annual' ? 'primary' : 'infor'"
              @click="toGetDialogChartCompared('annual')"
            >
              年
            </el-button>
            <span style="margin-left: 12px">
              <el-checkbox v-model="currentChartLinkage">图形联动</el-checkbox>
            </span>
            <span style="margin-left: 8px">
              <el-checkbox
                v-model="currentDialogChartData.showWatermark"
                @change="toggleDialogChartWatermark">
                水印
              </el-checkbox>
            </span>
          </span>
        </div>
        <div
          v-loading="currentDialogChartData.compareLoading"
          element-loading-spinner="el-icon-loading"
        >
          <span>截至{{ currentDialogLinkRatios[0].datadate }},</span>
          <span v-for="(lk, lki) in currentDialogLinkRatios" :key="lki">
            {{ lk.name }}报{{ lk.datavalue }}{{ lk.unit }},环比
            {{ lk.link_ratio >= 0 ? '上涨' : '下跌' }}
            <span :class="lk.link_ratio >= 0 ? 'up-red' : 'up-green'">
              {{ Math.abs(lk.link_ratio * 100).toFixed(2) }}%
            </span>
            ;
          </span>
        </div>
      </div>
    </el-dialog>

    <!-- 设置图形参数的弹窗 -->
    <el-dialog :visible.sync="showOptionDialog" title="修改图形配置">
      <div style="padding: 0 20px">
        <el-row :gutter="1" type="flex" align="middle">
          <el-col :span="4">标题：</el-col>
          <el-col :span="20">
            <el-input v-model="curChartOptionObj.name"></el-input>
          </el-col>
        </el-row>
        <br />
        <el-row :gutter="1" type="flex" align="middle">
          <el-col :span="4">横轴格式：</el-col>
          <el-col :span="8">
            <el-select v-model="curChartOptionObj.xaxis_format" size="mini">
              <el-option value="%Y-%m-%d" label="日"></el-option>
              <el-option value="%Y-%m" label="月"></el-option>
              <el-option value="%Y" label="年"></el-option>
            </el-select>
          </el-col>
          <el-col :span="3" :offset="1">旋转角度：</el-col>
          <el-col :span="8">
            <el-input-number
              v-model="curChartOptionObj.xaxis_rotate"
              :min="-90"
              :max="90"
            ></el-input-number>
          </el-col>
        </el-row>
        <br />
        <el-row :gutter="1" type="flex" align="middle">
          <el-col :span="4">开始日期：</el-col>
          <el-col :span="8">
            <el-date-picker
              v-model="curChartOptionObj.startdate"
              placeholder="不填则不限制"
            ></el-date-picker>
          </el-col>
          <el-col :span="3" :offset="1">结束日期：</el-col>
          <el-col :span="8">
            <el-date-picker
              v-model="curChartOptionObj.enddate"
              placeholder="不填则不限制"
            ></el-date-picker>
          </el-col>
        </el-row>
        <br />
        <el-row :gutter="1" type="flex" align="middle">
          <el-col :span="4">左轴最小：</el-col>
          <el-col :span="8">
            <el-input
              v-model.trim="curChartOptionObj.left_min"
              clearable
              placeholder="设置左轴最小值"
            ></el-input>
          </el-col>
          <el-col :span="3" :offset="1">左轴最大：</el-col>
          <el-col :span="8">
            <el-input
              v-model.trim="curChartOptionObj.left_max"
              clearable
              placeholder="设置左轴最大值"
            ></el-input>
          </el-col>
        </el-row>
        <br />
        <el-row :gutter="1" type="flex" align="middle">
          <el-col :span="4">右轴最小：</el-col>
          <el-col :span="8">
            <el-input
              v-model.trim="curChartOptionObj.right_min"
              clearable
              placeholder="设置右轴最小值"
            ></el-input>
          </el-col>
          <el-col :span="3" :offset="1">右轴最大：</el-col>
          <el-col :span="8">
            <el-input
              v-model.trim="curChartOptionObj.right_max"
              clearable
              placeholder="设置右轴最大值"
            ></el-input>
          </el-col>
        </el-row>
        <br />
        <el-row :gutter="1" type="flex" align="middle">
          <el-col :span="4">水印：</el-col>
          <el-col :span="20">
            <el-input
              v-model.trim="curChartOptionObj.watermark"
              clearable
              placeholder="不填则不显示水印"
            ></el-input>
          </el-col>
        </el-row>
        <br />
        <el-row :gutter="1" type="flex" align="middle">
          <el-col :span="4">排序：</el-col>
          <el-col :span="20">
            <el-input
              v-model.trim="curChartOptionObj.sorted"
              clearable
              placeholder="数据越大越靠后,不填则默认1"
            ></el-input>
          </el-col>
        </el-row>
      </div>
      <div slot="footer">
        <el-button
          type="primary"
          :loading="modifyLoading"
          @click="toModifyChart"
        >
          确认修改
        </el-button>
      </div>
    </el-dialog>

    <!-- 查看表数据弹窗 -->
    <el-dialog
      :visible.sync="showSheetDialog"
      :title="currentDialogSheetName"
      width="50%"
      top="2%"
    >
      <el-table border :data="sheetDataList" height="70vh">
        <el-table-column
          prop="datadate"
          label="日期"
          width="100px"
        ></el-table-column>
        <el-table-column
          v-for="(item, index) in sheetDataColumns"
          :key="index"
          show-overflow-tooltip
          :prop="item.prop"
          :label="item.name"
          width="250px"
        ></el-table-column>
      </el-table>
      <el-pagination
        style="margin-top: 5px"
        background
        :current-page="sheetDataPage"
        :page-size="sheetDataPageSize"
        layout="total, prev, pager, next, jumper"
        :total="sheetDataTotalCount"
        @current-change="sheetDataPageChange"
      ></el-pagination>
    </el-dialog>

    <!-- 查看数据表相关图形弹窗 -->
    <el-dialog
      v-if="showSheetChartDialog"
      :visible.sync="showSheetChartDialog"
      title="数据表下的图形"
      width="50%"
      top="2%"
    >
      <div class="chart-container">
        <div v-for="(item, index) in currentSheetChartList" :key="item.id">
          <div class="chart-card">
            <span class="action-btns">
              <el-button
                circle
                icon="el-icon-s-operation"
                type="primary"
                @click="optionMyChart(index)"
              ></el-button>
              <el-button
                circle
                icon="el-icon-delete"
                type="danger"
                @click="delMyChart(index)"
              ></el-button>
            </span>
            <div style="height: 300px; width: 500px; position: relative">
              <vab-chart
                autoresize
                theme="vab-echarts-theme"
                :option="item.option"
              ></vab-chart>
              <div style="font-size: 20px; color: rgba(0, 0, 0, 0.2)">
                <div style="position: absolute; top: 96px; left: 80px">
                  {{ item.watermark }}
                </div>
                <div style="position: absolute; top: 180px; right: 80px">
                  {{ item.watermark }}
                </div>
              </div>
            </div>
            <span class="chart-info">
              <span>{{ item.sorted }}</span>
            </span>
          </div>
        </div>
      </div>
    </el-dialog>
    <!-- 配置分组的弹窗 -->
    <el-dialog
      :visible.sync="showEditGroupDialog"
      title="分组配置"
      width="480px"
    >
      <div style="padding: 0px 35px 15px 35px; line-height: 36px">
        <!-- 编辑分组列表 -->
        <div v-for="g in folderList.slice(1)" :key="g.id" class="folder-box">
          <vab-icon :icon="['fas', 'folder']" class="folder-icon"></vab-icon>
          <span v-if="curEditFolderId === g.id">
            <el-input
              v-model="g.name"
              size="mini"
              style="width: 320px"
            ></el-input>
          </span>
          <span
            v-else
            class="folder-name"
            style="cursor: auto"
            @click="toEditGroupName(g)"
          >
            {{ g.name }}
          </span>
          <div class="folder-actions">
            <vab-icon
              v-if="curEditFolderId === g.id"
              :icon="['fas', 'save']"
              class="save-icon"
              @click="toSaveEditGroupName(g)"
            ></vab-icon>
            <vab-icon
              v-else
              :icon="['fas', 'edit']"
              class="edit-icon"
              @click="toEditGroupName(g)"
            ></vab-icon>
            <vab-icon
              :icon="['fas', 'trash-alt']"
              class="trash-icon"
              @click="toDeleteGroupName(g)"
            ></vab-icon>
          </div>
        </div>
        <div style="margin-top: 15px">
          <el-divider size="mini">
            新建【{{ curTabName === 'chartList' ? '图形库' : '表格库' }}】分组
          </el-divider>
          <el-input
            v-model="currentGroupName"
            placeholder="请输入分组名称"
            size="mini"
            style="width: 270px; margin-right: 10px"
          ></el-input>
          <el-button size="mini" type="primary" @click="saveNewGroupName">
            确定
          </el-button>
          <el-button
            size="mini"
            type="infor"
            @click="showEditGroupDialog = false"
          >
            取消
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  let NAME_SPACE = 'V03'
  import html2canvas from 'html2canvas'
  import VabChart from '@/plugins/echarts'
  import { datetimeToStr } from '@/utils/datetimeUtils'
  import { getUserAuthVariety } from '@/api/operations/variety'
  import {
    getVarietyChart,
    getChartOption,
    getVarietySheet,
    getSheetData,
    getSheetCharts,
    getChartCompares,
  } from '@/api/edbdata/variety'
  import {
    delSheet,
    delChart,
    modifyChartOption,
    saveDatalibGroup,
    getDatalibGroups,
    modifyChartGroup,
    modifySheetGroup,
    deleteDatalibGroup,
  } from '@/api/edbdata/personal'
  export default {
    components: {
      VabChart,
    },
    data() {
      return {
        useNewColors: true,
        isShowOwn: true,
        reqOptionTimer: null,
        reqOptionIndex: -1,
        curTabName: 'chartList',
        chartListLable: '图形列表[0]',
        chartTabLabel: '图形一览[0]',
        sheetTabLabel: '数据表[0]',
        varietyList: [],
        curVariety: '',
        dataListLoading: false,
        chartList: [],
        sheetList: [],
        curOptionChartIndex: -1, // 当前点击配置的的图形下标
        showOptionDialog: false,
        curChartOptionObj: {
          chart_id: -1,
          name: '',
          xaxis_format: '',
          xaxis_rotate: 0,
          startdate: null,
          enddate: null,
          watermark: '',
          sorted: null,
          left_min: null,
          left_max: null,
          right_min: null,
          right_max: null,
        },
        modifyLoading: false,

        showChartDialog: false,
        currentDialogChartName: '',
        currentDialogChartOption: null,
        currentDialogLinkRatios: [],
        currentChartLinkage: true, // 当前图形联动频率
        currentDialogChartWatermark: '',
        currentDialogChartData: {
          compared: 'day',
          chartId: -1,
          compareLoading: false,
          showWatermark: true,
        },

        // 查询数据详情
        showSheetDialog: false,
        currentDialogSheetName: '',
        sheetDataCache: [],
        sheetDataList: [],
        sheetDataColumns: [],
        sheetDataPage: 1,
        sheetDataPageSize: 100,
        sheetDataTotalCount: 0,

        // 当前数据表下的图形
        currentSheetChartList: [],
        showSheetChartDialog: false,

        keyword: '', // 查询的关键字,
        folderList: [],
        showEditGroupDialog: false,
        folderOpenId: 0,
        currentGroupName: '',
        lastSheetFolderId: 0,
        lastChartFolderId: 0,
        curEditFolderId: -1,
        curEditFolderName: '',
      }
    },
    watch: {
      reqOptionIndex(n, o) {
        // console.log(n, o);
        if (n < 0) return false
        if (n >= this.chartList.length) {
          clearInterval(this.reqOptionTimer)
          this.reqOptionIndex = -1
          this.reqOptionTimer = true // 清除定时器
          return false
        }
        this.getChartFactOption(n)
      },
      curTabName(n, o) {
        const temp = ['chart', 'chartList']
        if (temp.indexOf(n) > -1 && temp.indexOf(o) > -1) {
          return
        }
        this.refreshGroupNames()
        this.folderOpenId =
          n === 'sheet' ? this.lastSheetFolderId : this.lastChartFolderId
      },
    },
    mounted() {
      this.getVariety()
    },
    methods: {
      getVariety() {
        getUserAuthVariety({ space: NAME_SPACE }).then((res) => {
          this.varietyList = res.data
        })
      },

      // 弹窗的图形解读（弹窗的）
      toGetDialogChartCompared(comparedType) {
        this.currentDialogChartData.compareLoading = true
        getChartCompares({
          cid: this.currentDialogChartData.chartId,
          compare: comparedType,
        }).then((res) => {
          this.currentDialogLinkRatios = res.data.link_ratios
          this.currentDialogChartData.compareLoading = false
          this.currentDialogChartData.compared = comparedType
          // 设置图形配置
          if (this.currentChartLinkage) {
            this.currentDialogChartOption = res.data.chart_option // 图形联动
          }
        })
      },

      // 获取图形的对比解读(图形列表)
      toGetChartCompared(index, comparedType) {
        let cObj = this.chartList[index]
        if (cObj.editCompared) {
          this.$baseMessage('您正在编辑对比解读，请先退出!', 'error')
          return
        }
        cObj.compareLoading = true
        getChartCompares({ cid: cObj.id, compare: comparedType }).then(
          (res) => {
            cObj.link_ratios = res.data.link_ratios
            cObj.compared = res.data.compared
            cObj.compareText = this.orginazeComparteText(cObj.link_ratios, true)
            cObj.compareLoading = false
            if (cObj.linkage) {
              cObj.option = res.data.chart_option // 图形联动水印
            }
            this.chartList.splice(index, 1, cObj)
          }
        )
      },

      // 组织对比解读文字
      orginazeComparteText(link_ratios, colored) {
        let compareText = ''
        if (link_ratios.length > 0) {
          compareText += `截至${link_ratios[0].datadate},`
          for (let i = 0; i < link_ratios.length; i++) {
            const lr = link_ratios[i]
            compareText += `${lr.name}报${lr.datavalue}${lr.unit},环比`
            compareText += `${lr.link_ratio > 0 ? '上涨' : '下跌'}`
            if (colored) {
              compareText += `<span class=${
                lr.link_ratio > 0 ? 'up-red' : 'up-green'
              }>`
              compareText += `${Math.abs(lr.link_ratio * 100).toFixed(2)}%</span>`
            } else {
              compareText += `${Math.abs(lr.link_ratio * 100).toFixed(2)}%`
            }
          }
        }
        return compareText
      },

      // 编辑对比解读
      toEditCompareText(cObj) {
        cObj.comparePlainText = this.orginazeComparteText(cObj.link_ratios, false)
        cObj.editCompared = true
      },

      // 临时确定对比解读
      toStoreCompareText(cObj) {
        cObj.compareText = cObj.comparePlainText
        cObj.editCompared = false
      },
      // 图形组别发生改变
      chartGroupChanged(groupId, row, index) {
        modifyChartGroup({
          chart_id: row.id,
          group_id: groupId,
        }).then((res) => {
          if (res.code === 200) {
            this.$baseMessage(res.msg, 'success')
            this.chartList.splice(index, 1)
          }
        })
      },

      // 表组别发生变化
      sheetGroupChanged(groupId, row, index) {
        modifySheetGroup({
          sheet_id: row.id,
          group_id: groupId,
        }).then((res) => {
          if (res.code === 200) {
            this.$baseMessage(res.msg, 'success')
            this.sheetList.splice(index, 1)
          }
        })
      },

      // 显示组别下的内容
      toShowGroupContents(groupItem) {
        this.folderOpenId = groupItem.id
        // 根据组类别刷新图或表的数据
        if (groupItem.group_type === 'chart') {
          this.refreshVarietyCharts()
          this.lastChartFolderId = this.folderOpenId
        } else if (groupItem.group_type === 'sheet') {
          this.refreshVarietySheets()
          this.lastSheetFolderId = this.folderOpenId
        }
      },

      // 新建组别
      toCreateNewGroup() {
        this.$baseMessage('分组功能暂时关闭,等确定修改后开放!', 'error')
        return
        this.curEditFolderId = -1
        this.curEditFolderName = ''
        this.currentGroupName = ''
        this.showEditGroupDialog = true
      },

      // 准备编辑组别
      toEditGroupName(group) {
        this.curEditFolderId = group.id
        this.curEditFolderName = group.name
      },

      // 保存编辑的组别
      toSaveEditGroupName(group) {
        saveDatalibGroup(group).then((res) => {
          if (res.code === 200) {
            this.$baseMessage(res.msg, 'success')
            this.curEditFolderId = -1
            this.curEditFolderName = ''
          } else {
            this.$baseMessage(res.msg, 'error')
          }
        })
      },

      // 删除组别
      toDeleteGroupName(group) {
        if (this.curEditFolderId === group.id) {
          this.curEditFolderId = -1
          group.name = this.curEditFolderName
          return
        }
        // 删除
        this.$baseConfirm(
          '确定删除数据组别吗?操作不可恢复!',
          '删除确认',
          () => {
            console.log('确定删除!')
            deleteDatalibGroup(group).then((res) => {
              if (res.code === 200) {
                this.$baseMessage(res.msg, 'success')
                this.refreshGroupNames()
              } else {
                this.$baseMessage(res.msg, 'error')
              }
            })
          }
        )
      },

      // 保存组别
      saveNewGroupName() {
        const groupItem = {
          name: this.currentGroupName.trim(),
          group_type: this.curTabName === 'sheet' ? 'sheet' : 'chart',
          variety_en: this.curVariety,
        }
        if (!groupItem.variety_en) {
          this.$baseMessage('请先选择品种再操作!', 'error')
          return
        }
        if (!groupItem.name) {
          this.$baseMessage('请填写组别名称！', 'error')
          return
        }
        saveDatalibGroup(groupItem).then((res) => {
          if (res.code === 200) {
            this.$baseMessage(res.msg, 'success')
            this.showEditGroupDialog = false
            this.currentGroupName = ''
            this.refreshGroupNames()
          } else {
            this.$baseMessage(res.msg, 'error')
          }
        })
      },

      // 查询组别
      refreshGroupNames() {
        if (!this.curVariety) return
        const reqType = this.curTabName === 'sheet' ? 'sheet' : 'chart'
        const params = {
          v: this.curVariety,
          t: reqType,
        }
        this.folderOpenId = 0
        getDatalibGroups(params).then((res) => {
          this.folderList = res.data
        })
      },

      // tab标签点击
      tabClickEvent(tab) {
        if (tab.name === 'chart' && this.reqOptionTimer === null) {
          // 启动定时器获取图形
          this.reqOptionIndex = 0
          this.reqOptionTimer = setInterval(() => {
            this.reqOptionIndex += 1
          }, 400)
        } else if (tab.name === 'sheet' && this.sheetDataList.length < 1) {
          // 请求sheet
          this.refreshVarietySheets()
        }
      },

      // 复制弹窗图形
      toCopyPopupChart() {
        let div = document.getElementById('dialogChart')
        this.copyForImage(div)
      },

      // 复制图形
      toCopyChart(cIndex) {
        let chartItem = this.chartList[cIndex]
        let refName = 'chartDiv' + chartItem.id
        let div = document.getElementById(refName)
        this.copyForImage(div)
      },

      // 复制
      copyForImage(docElement) {
        html2canvas(docElement, { backgroundColor: '#fff' }).then((canvas) => {
          // console.log(canvas);
          // 将canvas转为blob对象
          canvas.toBlob((blob) => {
            // 将blob对象放入剪切板item中
            // eslint-disable-next-line no-undef
            const data = [new ClipboardItem({ [blob.type]: blob })]
            // 写入剪切板,成功会执行resolve,失败则走reject
            navigator.clipboard.write(data).then(
              () => {
                this.$message({
                  message: '图片已保存到粘贴板',
                  type: 'success',
                  duration: 2000,
                })
              },
              () => {
                this.$message({
                  message: '保存截图失败',
                  type: 'warning',
                  duration: 2000,
                })
              }
            )
          }, 'image/png')
        })
      },

      // 品种选择变化
      handleVarietyChange() {
        this.refreshGroupNames() // 查询组别
        const reqType = this.curTabName === 'sheet' ? 'sheet' : 'chart'
        if (reqType === 'chart') {
          this.refreshVarietyCharts()
        } else {
          this.refreshVarietySheets()
        }
      },

      // 获取品种表
      refreshVarietySheets() {
        if (!this.curVariety) return false
        this.dataListLoading = true
        const queryParams = {
          variety: this.curVariety,
          own: this.isShowOwn ? 1 : 0,
          group: this.folderOpenId,
        }
        getVarietySheet(queryParams).then((res) => {
          this.sheetList = res.data.filter((item) => {
            if (this.keyword) {
              return item.name.match(new RegExp(this.keyword))
            } else {
              return true
            }
          })
          this.sheetTabLabel = '数据表[' + this.sheetList.length + ']'
          this.dataListLoading = false
        })
      },

      // 弹窗显示表数据
      toShowSheetPopup(cIndex) {
        let sheetObj = this.sheetList[cIndex]
        this.currentDialogSheetName = sheetObj.name
        getSheetData({ sid: sheetObj.id }).then((res) => {
          this.showSheetDialog = true
          const data = res.data
          this.sheetDataCache = data.table_value
          this.sheetDataCache.sort(this.sortList('datadate', false))
          this.sheetDataColumns = data.table_header
          this.sheetDataTotalCount = this.sheetDataCache.length
          this.showSheetData()
        })
      },

      // 显示数据
      showSheetData() {
        let startIndex = (this.sheetDataPage - 1) * this.sheetDataPageSize
        this.sheetDataList = JSON.parse(
          JSON.stringify(
            this.sheetDataCache.slice(
              startIndex,
              startIndex + this.sheetDataPageSize
            )
          )
        )
      },

      // 导出数据文件
      toExportSheetData(cIndex) {
        let sheetObj = this.sheetList[cIndex]
        console.log(sheetObj)
        const bodyData = {
          sid: sheetObj.id,
          filename: sheetObj.name,
        }
        getSheetData(bodyData).then((res) => {
          let a = document.createElement('a')
          a.href = res.data.file_url
          a.style.display = 'none'
          document.body.appendChild(a)
          a.click()
          document.body.removeChild(a)
        })
      },

      // 数据页码变化
      sheetDataPageChange(page) {
        this.sheetDataPage = page
        this.showSheetData()
      },

      // 删除数据表
      delMySheet(sheetIndex) {
        let sheetObj = this.sheetList[sheetIndex]
        this.$baseConfirm(
          '你确定要删除数据表吗？删除不可恢复!',
          null,
          async () => {
            delSheet(sheetObj.id).then((res) => {
              this.$baseMessage(res.msg, 'success')
              this.sheetList.splice(sheetIndex, 1) // 移除当前列表中的数据
              // 修改显示的数据
              this.sheetTabLabel = '数据表[' + this.sheetList.length + ']'
            })
          }
        )
      },

      // 弹窗显示表相关图形
      toShowSheetCharts(sIndex) {
        let sheetObj = this.sheetList[sIndex]
        getSheetCharts({ sid: sheetObj.id }).then((res) => {
          this.currentSheetChartList = res.data
          if (
            this.currentSheetChartList &&
            this.currentSheetChartList.length > 0
          ) {
            // 弹窗显示图形
            this.showSheetChartDialog = true
            // 请求获取图形配置参数
            let chartLength = this.currentSheetChartList.length
            for (let i = 0; i < chartLength; i++) {
              let chartObj = this.currentSheetChartList[i]
              getChartOption(chartObj.id, this.useNewColors).then((res) => {
                chartObj.option = res.data.chart_option
                chartObj.link_ratios = res.data.link_ratios
              })
            }
          } else {
            this.$baseMessage('该表下还没有图形。', 'infor')
          }
        })
      },

      // 获取品种图
      refreshVarietyCharts() {
        if (!this.curVariety) return false
        this.chartList = []
        this.dataListLoading = true
        const queryParams = {
          variety: this.curVariety,
          own: this.isShowOwn ? 1 : 0,
          group: this.folderOpenId,
        }
        getVarietyChart(queryParams).then((res) => {
          let chartList = res.data.filter((item) => {
            if (this.keyword) {
              return item.name.match(new RegExp(this.keyword))
            } else {
              return true
            }
          })
          this.chartList = chartList.map((item) => {
            item.editCompared = false
            item.compared = 'day'
            item.compareText = ''
            item.comparePlainText = ''
            item.linkage = true // 图形联动标记
            item.showWatermark = true // 水印显示标记
            return item
          })
          this.dataListLoading = false
          this.chartTabLabel = '图形一览[' + this.chartList.length + ']'
          this.chartListLable = '图形列表[' + this.chartList.length + ']'
          clearInterval(this.reqOptionTimer)
          this.reqOptionTimer = null
          if (this.curTabName === 'chart') {
            // 在显示图形页面才启动定时器自动请求图形配置
            this.reqOptionIndex = 0
            this.reqOptionTimer = setInterval(() => {
              this.reqOptionIndex += 1
            }, 400)
          }
        })
      },

      // 弹窗显示图形
      toShowChartPopup(cIndex) {
        // 在弹窗中加入了v-if,每次弹窗新初始化dom，避免了vue-echarts的缓存，使图形不准确
        let chartObj = this.chartList[cIndex]
        this.currentDialogChartWatermark = chartObj.watermark
        this.currentDialogChartName = chartObj.name
        this.currentDialogChartData.chartId = chartObj.id
        this.currentDialogChartData.compared = 'day'
        this.currentDialogChartOption = {} // 清空配置
        // this.currentDialogChartOption = JSON.parse(JSON.stringify(chartObj.option))

        // 网络请求图形配置
        if (!chartObj.option.chart_id) {
          getChartOption(chartObj.id, this.useNewColors).then((res) => {
            this.currentDialogChartOption = res.data.chart_option
            this.currentDialogLinkRatios = res.data.link_ratios
          })
        } else {
          this.currentDialogChartOption = JSON.parse(
            JSON.stringify(chartObj.option)
          )
          this.currentDialogLinkRatios = JSON.parse(
            JSON.stringify(chartObj.link_ratios)
          )
        }
        this.showChartDialog = true
      },

      // 获取各图形的配置
      getChartFactOption(cIndex) {
        let chartObj = this.chartList[cIndex]
        getChartOption(chartObj.id, this.useNewColors).then((res) => {
          const link_ratios = res.data.link_ratios
          chartObj.option = res.data.chart_option
          chartObj.link_ratios = link_ratios
          chartObj.compared = res.data.compared
          chartObj.compareText = this.orginazeComparteText(link_ratios, true)
        })
      },

      // 删除图形
      delMyChart(chartIndex) {
        let chartObj = this.chartList[chartIndex]
        this.$baseConfirm('你确定要删除图形，删除不可恢复!', null, async () => {
          delChart(chartObj.id).then((res) => {
            this.$baseMessage(res.msg, 'success')
            this.chartList.splice(chartIndex, 1) // 移除当前图形列表中的数据
            // 设置显示数字
            this.chartTabLabel = '图形一览[' + this.chartList.length + ']'
            this.chartListLable = '图形列表[' + this.chartList.length + ']'
          })
        })
      },
      // 隐藏和显示水印
      toggleWatermark(chartIndex, isShow) {
        let chartObj = this.chartList[chartIndex]
        chartObj.showWatermark = isShow
      },
      // 隐藏和显示当前弹窗图形的水印
      toggleDialogChartWatermark(isShow) {
        this.currentDialogChartData.showWatermark = isShow
      },

      // 准备配置图形
      optionMyChart(chartIndex) {
        this.curOptionChartIndex = chartIndex
        let chartObj = this.chartList[this.curOptionChartIndex]
        if (!chartObj.option.chart_id) {
          // 配置还未返回时，只能先请求数据，避免点击产生错误
          getChartOption(chartObj.id, this.useNewColors).then((res) => {
            chartObj.option = JSON.parse(JSON.stringify(res.data.chart_option))
            this.curChartOptionObj.left_min = chartObj.option.yAxis[0].min
            this.curChartOptionObj.left_max = chartObj.option.yAxis[0].max
            this.curChartOptionObj.right_min = chartObj.option.yAxis[1].min
            this.curChartOptionObj.right_max = chartObj.option.yAxis[1].max
          })
        }
        this.curChartOptionObj.chart_id = chartObj.id
        this.curChartOptionObj.name = chartObj.name
        this.curChartOptionObj.xaxis_format = chartObj.xaxis_format
        this.curChartOptionObj.startdate = chartObj.startdate
        this.curChartOptionObj.enddate = chartObj.enddate
        this.curChartOptionObj.watermark = chartObj.watermark
        this.curChartOptionObj.sorted = chartObj.sorted
        this.showOptionDialog = true
      },

      // 确认修改
      toModifyChart() {
        this.curChartOptionObj.startdate = datetimeToStr(
          this.curChartOptionObj.startdate,
          true,
          '-'
        )
        this.curChartOptionObj.enddate = datetimeToStr(
          this.curChartOptionObj.enddate,
          true,
          '-'
        )
        if (
          !this.curChartOptionObj.left_min &&
          this.curChartOptionObj.left_min !== 0
        ) {
          this.curChartOptionObj.left_min = null
        }
        if (
          !this.curChartOptionObj.left_max &&
          this.curChartOptionObj.left_max !== 0
        ) {
          this.curChartOptionObj.left_max = null
        }
        if (
          !this.curChartOptionObj.right_min &&
          this.curChartOptionObj.right_min !== 0
        ) {
          this.curChartOptionObj.right_min = null
        }
        if (
          !this.curChartOptionObj.right_max &&
          this.curChartOptionObj.right_max !== 0
        ) {
          this.curChartOptionObj.right_max = null
        }
        modifyChartOption(this.curChartOptionObj).then((res) => {
          this.$baseMessage(res.msg, 'success')
          this.showOptionDialog = false
          // 刷新当前数据下的图形配置
          this.getChartFactOption(this.curOptionChartIndex)
          // 修改图形的其他参数(排序等)
          let chartObj = this.chartList[this.curOptionChartIndex]
          chartObj.name = res.data.name
          chartObj.watermark = res.data.watermark
          chartObj.sorted = res.data.sorted
          chartObj.startdate = res.data.startdate
          chartObj.enddate = res.data.enddate
          this.chartList.sort(this.sortList('sorted', true))
          // 恢复关键数据
          this.curChartOptionObj.chart_id = -1
          this.curOptionChartIndex = -1
        })
      },

      // 排序数据方法
      sortList(key, asc) {
        if (asc) {
          return (a, b) => (a[key] >= b[key] ? 1 : -1)
        } else {
          return (a, b) => (a[key] >= b[key] ? -1 : 1)
        }
      },
    },
  }
</script>

<style scoped lang="scss">
  .table-select {
    .el-select ::v-deep .el-input__inner {
      border: none;
      box-shadow: none;
    }
  }
  .folders {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    margin-bottom: 5px;
  }
  .folder-box {
    margin-right: 15px;
    .folder-icon {
      color: #f7d673;
      margin-right: 4px;
    }
    .folder-name {
      cursor: pointer;
      &:hover {
        color: #349cfc;
      }
    }
    &:hover {
      .folder-actions {
        @extend .show-btns;
      }
    }
  }
  .folder-actions {
    float: right;
    cursor: pointer;
    opacity: 0;
    .edit-icon,
    .save-icon {
      color: #349cfc;
      margin-right: 15px;
    }
    .trash-icon {
      color: #ff430d;
    }
  }
  .chart-container {
    display: flex;
    align-items: center;
    flex-flow: wrap;
    height: 75vh;
    overflow: auto;
  }
  #dialogChart {
    height: 300px;
    width: 500px;
    position: relative;
    padding-left: 20px;
  }
  .show-btns {
    opacity: 1;
  }
  .chart-card {
    position: relative;
    box-shadow: 0px 2px 12px 0px rgba(0, 0, 0, 0.1);
    padding: 10px;
    margin-right: 8px;
    margin-bottom: 8px;
    border-radius: 5px;
    .el-button {
      transform: scale(0.7); // 缩小按钮
      & + .el-button {
        margin-left: -1px;
      }
    }
    .action-btns {
      z-index: 9999;
      opacity: 0;
      transition: opacity 0.1s;
      position: absolute;
      top: 0;
      right: 0;
    }
    &:hover {
      background-color: rgba(245, 245, 245, 0.4);
      .action-btns,
      .chart-info,
      .compared-box {
        @extend .show-btns;
      }
    }
    .chart-info {
      opacity: 0;
      display: inline-block;
      transition: opacity 0.1s;
      position: absolute;
      right: 8px;
      bottom: 4px;
      font-size: 8px;
    }
  }
  .link-ratio-box {
    border-top: 1px dashed #999;
    text-align: 2em;
    margin-top: 8px;
    line-height: 22px;
    width: 480px;
    padding: 4px 10px;
    ::v-deep .up-red {
      color: #ff430d;
    }
    ::v-deep .up-green {
      color: #34e073;
    }
    .compared-box {
      opacity: 0;
    }
    &:hover {
      .compared-box {
        @extend .show-btns;
      }
    }
  }
</style>
